package com.ddw.wotcg.server.controllers;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ddw.wotcg.server.utils.RequestHelper;
import com.ddw.wotcg.server.utils.User;
import com.ddw.wotcg.server.utils.UserHelper;

@SuppressWarnings("serial")
public class SignOutController extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		final Map<String, String> cookies = RequestHelper.parseCookies(req);
		final UUID session = RequestHelper.getSession(cookies);
		final User user = UserHelper.bySession(session);
		
		// If user is not logged in then redirect them
		if (user == null) {
			resp.sendRedirect("/home");
			return;
		}
		
		// Remove session
		user.session = null;
		user.sessionCreated = null;
		UserHelper.save(user);
		
		// Set an expired cookie
		final Cookie cookie = new Cookie(RequestHelper.SESSION_COOKIE, null);
		cookie.setMaxAge(0);
		resp.addCookie(cookie);
		resp.sendRedirect("/home");
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
}
